<script setup lang="tsx">
// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 模块导入 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

import { NButton, NPopconfirm } from 'naive-ui';
import type { Ref } from 'vue';
import { ref } from 'vue';
import dayjs from 'dayjs';
import { useAppStore } from '@/store/modules/app';
import { useAuth } from '@/hooks/business/auth';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { transDeleteParams } from '@/utils/common';
import { fetchDeleteCjProject, fetchGetCjProjectPage } from '@/service/api';
import { useDict } from '@/hooks/business/dict';
import ProjectSearch from './modules/project-search.vue';
import type { OperateType } from './modules/project-operate-drawer.vue';
import ProjectOperateDrawer from './modules/project-operate-drawer.vue';

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组件名称 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

defineOptions({
  name: 'CjProjectPage'
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组合式函数 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

const appStore = useAppStore();

const { hasAuth } = useAuth();

const { dictLabel } = useDict();

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 父子传参 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架模型 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

const operateType = ref<OperateType>('add');

const editingData: Ref<Api.Sampling.Project | null> = ref(null);

const { columns, columnChecks, data, loading, getData, getDataByPage, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchGetCjProjectPage,
  showTotal: true,
  apiParams: {
    page: 1,
    pageSize: 20,
    name: ''
  },
  columns: () => [
    {
      key: 'code',
      title: $t('page.sampling.project.code'),
      align: 'center',
      minWidth: 100
    },
    {
      key: 'name',
      title: $t('page.sampling.project.name'),
      align: 'center',
      minWidth: 100
    },
    {
      key: 'projectType',
      title: $t('page.sampling.project.projectType'),
      align: 'center',
      minWidth: 100,
      render: (row) => dictLabel('cj_project_type', row.projectType)
    },
    {
      key: 'projectMode',
      title: $t('page.sampling.project.projectMode'),
      align: 'center',
      minWidth: 100,
      render: (row) => dictLabel('cj_project_mode', row.projectMode)
    },
    {
      key: 'description',
      title: $t('page.sampling.project.description'),
      align: 'center',
      minWidth: 100
    },
    {
      key: 'startDate',
      title: $t('page.sampling.project.startDate'),
      align: 'center',
      minWidth: 100,
      render: (row) => dayjs(row.startDate).format('YYYY-MM-DD')
    },
    {
      key: 'endDate',
      title: $t('page.sampling.project.endDate'),
      align: 'center',
      minWidth: 100,
      render: (row) => dayjs(row.endDate).format('YYYY-MM-DD')
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      minWidth: 200,
      render: (row) => (
        <div class="flex-center gap-8px">
          {hasAuth('cj:project:update') && (
            <NButton type="primary" quaternary size="small" onClick={() => edit(row)}>
              {$t('common.edit')}
            </NButton>
          )}
          {hasAuth('cj:project:delete') && (
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" quaternary size="small">
                    {$t('common.delete')}
                  </NButton>
                )
              }}
            </NPopconfirm>
          )}
        </div>
      )
    }
  ]
});

const { drawerVisible, openDrawer, checkedRowKeys, onDeleted, onBatchDeleted } = useTableOperate(data, getData);

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务模型 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架方法 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

function handleAdd() {
  operateType.value = 'add';
  openDrawer();
}

function edit(item: Api.Sampling.Project) {
  operateType.value = 'edit';
  editingData.value = { ...item };
  openDrawer();
}

async function handleDelete(id: string) {
  const { error, data: result } = await fetchDeleteCjProject(transDeleteParams([id]));
  if (!error && result) {
    await onDeleted();
  }
}

async function handleBatchDelete() {
  const { error, data: result } = await fetchDeleteCjProject(transDeleteParams(checkedRowKeys.value));
  if (!error && result) {
    await onBatchDeleted();
  }
}

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务方法 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架生命周期 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务生命周期 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-8px overflow-hidden lt-sm:overflow-auto">
    <ProjectSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard :bordered="false" class="sm:flex-1-hidden card-wrapper" content-class="flex-col">
      <TableHeaderOperation
        v-model:columns="columnChecks"
        :checked-row-keys="checkedRowKeys"
        :loading="loading"
        add-auth="cj:project:add"
        delete-auth="cj:project:delete"
        @add="handleAdd"
        @delete="handleBatchDelete"
        @refresh="getData"
      />
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        remote
        striped
        size="small"
        class="sm:h-full"
        :data="data"
        :scroll-x="962"
        :columns="columns"
        :flex-height="!appStore.isMobile"
        :loading="loading"
        :single-line="false"
        :row-key="(row) => row.id"
        :pagination="mobilePagination"
      />
      <ProjectOperateDrawer v-model:visible="drawerVisible" :operate-type="operateType" :row-data="editingData" @submitted="getDataByPage" />
    </NCard>
  </div>
</template>
